//
//  RegionHospitalDeskViewController.m
//  安好
//
//  Created by lianchuang on 14-12-8.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "RegionHospitalDeskViewController.h"

#import "HospitalTableViewCell.h"


@interface RegionHospitalDeskViewController ()<UITableViewDelegate,UITableViewDataSource>

/**
 *  左边的table
 */
@property(nonatomic,strong)UITableView * LeftTableView;
/**
 *  右边的table
 */
@property(nonatomic,strong)UITableView * RightTableView;

/**
 *  右边的数据
 */
@property(nonatomic,strong)NSMutableArray * rightDataArray;
/**
 * 左边的数据
 */
@property(nonatomic,strong)NSMutableArray * leftDataArray;
/**
 *  左table页面选中的省modal
 */
@property(nonatomic,strong)AreaModal * provinceModal;
/**
 * 左table页面选中的 父科室modal
 */
@property(nonatomic,strong)RegistrationDepartmentModal * departmentModal;

/**
 *  下拉加载页数
 */
@property (assign, nonatomic) NSInteger loadPage;

/**
 *  下拉右面的加载页数
 */
@property (assign, nonatomic) NSInteger loadRightPage;


@end

@implementation RegionHospitalDeskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeNavBar];
    [self loadData];
    [self makeTableView];
    
}
#pragma mark - 导航条设置
-(void)makeNavBar
{
    self.navigationItem.title = self.navBarTitle;
    //左按钮--返回
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

-(void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)loadData
{
    self.leftDataArray = [NSMutableArray arrayWithCapacity:0];
    self.rightDataArray = [NSMutableArray arrayWithCapacity:0];
    [self loadRequest];
    
   
}
-(void)loadRequest
{
    if ([self.loadRequestNum intValue] == 0) {
        //加载地区
        [self AFNetRequestForProvinceAndCity:self.provinceid];
    }
    if([self.loadRequestNum intValue] == 1)
    {
        self.loadPage = 1;
        [self AFNetRequestGetHospitalWithProvinceModal];
        
    }
    if ([self.loadRequestNum intValue] == 2) {
        self.loadPage = 1;
        [self AFNetRequestGetDepartment];

    }
    


}

#pragma mark - 这个请求某一个省下面的所有的市
//传“0”就是获取到所有的省，点击省的时候，把该省的provinceid传过来请求该省下面的所有市
-(void)AFNetRequestForProvinceAndCity:(NSString *)provinceid
{
    [self showActionView];
    
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/area/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"provinceid":provinceid};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);//失败
        }else
        {
            [self.rightDataArray removeAllObjects];
            for (NSDictionary * dic in responseObject[@"data"]) {
                AreaModal * modal = [[AreaModal alloc] initWithDic:dic];
                if ([provinceid intValue] == 0) {
                    [self.leftDataArray addObject:modal];
                    [self.LeftTableView reloadData];
                    self.LeftTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
                }else
                {
                    [self.rightDataArray addObject:modal];
                    [self.RightTableView reloadData];
                }
                
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
    }];


}
#pragma mark - AFNet获取某地区的医院
//获取该市下面的所有的医院，需要传省id，市id。获取到医院
-(void)AFNetRequestGetHospitalWithProvinceModal
{
    [self showActionView];
    MyNSLog("%d", self.loadPage);
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/hospital/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"provinceid":self.getProvinceModal.provinceid,@"cityid":self.getCityModal.cityid,@"page":[NSString stringWithFormat:@"%d",self.loadPage]};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {

            [self.LeftTableView footerEndRefreshing];
        }else
        {
            
            self.LeftTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            
            NSArray * hospitalArray = responseObject[@"data"];
            
            if (hospitalArray != nil ) {
                self.loadPage ++;
                
                for (NSDictionary * dic in hospitalArray) {
                    RegistrationHospitalModal * modal = [[RegistrationHospitalModal alloc] initWithDic:dic];
                    [self.leftDataArray addObject:modal];
                }
                [self.LeftTableView reloadData];
            }else if([hospitalArray count]< 20){
            
                [self.LeftTableView footerEndRefreshing];
            }else
            {
                if (self.loadPage > 1) {
                    MyNSLog("下拉无数据");
                }
            }
            [self.LeftTableView footerEndRefreshing];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
        [self.LeftTableView footerEndRefreshing];
    }];
    

}
#pragma mark - 获取某医院下面的科室
//在上面的请求中获取到医院，在这个请求中获取到该医院下面的科室，传参数医院id
-(void)AFNetRequestGetDepartment
{
    [self showActionView];
    
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/HospitalDepartment/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"hospitalid":self.getHospitalModal.hospitalid,@"page":[NSString stringWithFormat:@"%d",self.loadPage]};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self.LeftTableView footerEndRefreshing];
        }else
        {
            self.LeftTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            
            MyNSLog("%@", responseObject[@"data"]);
            NSArray * deskArray = responseObject[@"data"];
            if (deskArray != nil) {
                self.loadPage ++;
                for (NSDictionary * dic in deskArray) {
                    RegistrationDepartmentModal * modal = [[RegistrationDepartmentModal alloc] initWithDic:dic];
                    [self.leftDataArray addObject:modal];
                }
                [self.LeftTableView reloadData];
                
            }else if (deskArray.count < 20 ){
                [self.LeftTableView footerEndRefreshing];
            
            }else
            {
                if (self.loadPage>1) {
                    MyNSLog("上拉无数据");
                }
            }
             [self.LeftTableView footerEndRefreshing];

        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
         [self.LeftTableView footerEndRefreshing];
    }];

}
#pragma mark - 获取二级科室
-(void)AFNetRequestForChildDepartmend
{
    [self showActionView];
    MyNSLog("loadRightPage %d", self.loadRightPage);
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/HospitalDepartment/",kBaseURL];
    MyNSLog("hospdeptid : %@",self.departmentModal.hospdeptid );
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"hospitalid":self.getHospitalModal.hospitalid,@"page":[NSString stringWithFormat:@"%d",self.loadRightPage],@"parenthosdepid":self.departmentModal.hospdeptid};
    

    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
         MyNSLog("%@", responseObject);
        if ([statusString isEqualToString:@"0"]) {
            [self.RightTableView footerEndRefreshing];
        }else
        {
            MyNSLog("%@", responseObject[@"data"]);
            NSArray * childDeskArray = responseObject[@"data"];
            if (self.loadRightPage == 1) {
                [self.rightDataArray removeAllObjects];
                [self.RightTableView reloadData];
            }
            if (childDeskArray != nil) {
                self.loadRightPage ++;
                for (NSDictionary * dic in childDeskArray) {
                    RegistrationDepartmentModal * modal = [[RegistrationDepartmentModal alloc] initWithDic:dic];
                    [self.rightDataArray addObject:modal];
                }
                [self.RightTableView reloadData];
                
            }else if (childDeskArray.count < 20 ){
                [self.RightTableView footerEndRefreshing];
                
            }else
            {
                if (self.loadPage>1) {
                    MyNSLog("上拉无数据");
                }
            }
            [self.RightTableView footerEndRefreshing];
            
        }
            
 
        
    } failure:
    ^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self.RightTableView footerEndRefreshing];
        
    }];

}

-(void)makeTableView
{
    self.LeftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    [self.view addSubview:self.LeftTableView];
    self.LeftTableView.delegate = self;
    self.LeftTableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.LeftTableView.showsHorizontalScrollIndicator = NO;
    self.LeftTableView.showsVerticalScrollIndicator = NO;
    self.LeftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if ([self.loadRequestNum intValue] == 1) {
        [self.LeftTableView addFooterWithTarget:self action:@selector(AFNetRequestGetHospitalWithProvinceModal)];
    }
    if ([self.loadRequestNum intValue] == 2) {
        [self.LeftTableView addFooterWithTarget:self action:@selector(AFNetRequestGetDepartment)];
    }

    //左边的table
    self.RightTableView = [[UITableView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    [self.view addSubview:self.RightTableView];
    self.RightTableView.delegate = self;
    self.RightTableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.RightTableView.showsHorizontalScrollIndicator = NO;
    self.RightTableView.showsVerticalScrollIndicator = NO;
    self.RightTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.RightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.RightTableView.layer.backgroundColor =[ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16].CGColor;
    if ([self.loadRequestNum intValue] == 2) {
        [self.RightTableView addFooterWithTarget:self action:@selector(AFNetRequestForChildDepartmend)];
    }
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.LeftTableView) {
        return self.leftDataArray.count;
    }else if (tableView == self.RightTableView) {
        return self.rightDataArray.count;
    }else
    {
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.loadRequestNum intValue] == 1) {
        return 65;
    }else
    {
        return 44;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.LeftTableView) {
        //如果不是选中的医院
        if ([self.loadRequestNum intValue] != 1) {
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LeftID"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LeftID"];
            }
            //请求地区
            if ([self.loadRequestNum intValue] == 0) {
                AreaModal * modal = self.leftDataArray[indexPath.row];
                cell.textLabel.text = modal.name;
            }
            //请求的是科室
            if ([self.loadRequestNum intValue] == 2) {
                RegistrationDepartmentModal * modal = self.leftDataArray[indexPath.row];
                cell.textLabel.text = modal.departmentname;
            }
            
            return cell;
        }
        else//过来选医院
        {
            HospitalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"HospitalTableViewCell" owner:self options:nil] lastObject];
            }
            RegistrationHospitalModal * modal = self.leftDataArray[indexPath.row];
            cell.userLabel.text = modal.hospitalname;
            cell.goodLabel.text = modal.address;
            cell.leaveLabel.text = modal.levelname;
            [cell.userImageView setImageWithURL:[NSURL URLWithString:modal.picurl] placeholderImage:[UIImage imageNamed:@""]];
            
            return cell;
        }
        
    }
    else
    {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RightID"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RightID"];
        }
        
        if ([self.loadRequestNum intValue] == 0) {
            if (self.rightDataArray.count != 0) {
                AreaModal * modal = self.rightDataArray[indexPath.row];
                cell.textLabel.text = modal.name;
            }
        }
        
        if ([self.loadRequestNum intValue] == 2) {
            if (self.rightDataArray.count != 0) {
                RegistrationDepartmentModal * modal = self.rightDataArray[indexPath.row];
                cell.textLabel.text = modal.departmentname;
            }
        }
        
        return cell;
        
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击的时左边的tableView
    if (tableView == self.LeftTableView) {
       
        //点击的是地区
        if ([self.loadRequestNum intValue] == 0) {
            [UIView animateWithDuration:0.35 animations:^{
                self.LeftTableView.frame = CGRectMake(0, 0, kScreenWidth/3.0, kScreenHeight-iOS7TopMargin);
                self.RightTableView.frame = CGRectMake( kScreenWidth/3.0,0, kScreenWidth, kScreenHeight-iOS7TopMargin);
            }];
            //获取到该行的省id
            AreaModal * modal = self.leftDataArray[indexPath.row];
            self.provinceModal = modal;
            //网络请求把该省的id传过去，请求该省下面的所有的市
            [self AFNetRequestForProvinceAndCity:modal.provinceid];
        }
        
        
        //点击的是医院--这里医院没有科室选择，只有一个tableView
        if ([self.loadRequestNum intValue] == 1) {
            //获取到该医院的modal
            RegistrationHospitalModal * modal = self.leftDataArray[indexPath.row];
            [self.delegate getAreaProvinceModal:self.getProvinceModal andCityModal:self.getCityModal andHospitalModal:modal andParentDepartmentModal:nil andChildDepartment:nil];
            [self.navigationController popViewControllerAnimated:YES];
        
        }
        //点击的是父科室-
        if ([self.loadRequestNum intValue] == 2) {
            MyNSLog("%d", indexPath.row);
            //把父科室传上去
            self.departmentModal =self.leftDataArray[indexPath.row];
            [UIView animateWithDuration:0.35 animations:^{
                self.LeftTableView.frame = CGRectMake(0, 0, kScreenWidth/3.0+20, kScreenHeight-iOS7TopMargin);
                self.RightTableView.frame = CGRectMake( kScreenWidth/3.0+20,0, kScreenWidth, kScreenHeight-iOS7TopMargin);
            }];

            self.loadRightPage = 1;
            [self.rightDataArray removeAllObjects];
            [self.RightTableView reloadData];
            [self AFNetRequestForChildDepartmend];
        }
        
    }
    //点击的时右tableView，这个tableView只有在选择医院的时候不出像
    else
    {
        //点击的是地区
        if ([self.loadRequestNum intValue] == 0) {
            //这是cityModal
            AreaModal * modal = self.rightDataArray[indexPath.row];
            //把这人地区modal反向传值到上一个页面
            [self.delegate getAreaProvinceModal:self.provinceModal andCityModal:modal andHospitalModal:nil andParentDepartmentModal:nil andChildDepartment:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
        //点击获取子科室
        if ([self.loadRequestNum intValue] == 2) {
            MyNSLog("子科室  %d",indexPath.row );
            RegistrationDepartmentModal * modal = self.rightDataArray[indexPath.row];
            [self.delegate getAreaProvinceModal:self.getProvinceModal andCityModal:self.getCityModal andHospitalModal:self.getHospitalModal andParentDepartmentModal:self.departmentModal andChildDepartment:modal];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
    }

}



@end
